//
//  PersonChannelViewController.m
//  DemoV2
//
//  Created by 董一龙 on 2022/6/25.
//

#import "PersonChannelViewController.h"

@implementation PersonChannelViewController (CollectionViewDelegate)

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"section = %ld, item = %ld", indexPath.section, indexPath.item);
    // 非编辑状态点击无效
    if(!self.isEditState) return;
    // 第一个section点击cell无效，需要点击cell内的删除按钮
    if(indexPath.section == 0) return;
    // 非法输入无效
    if(indexPath.section >= self.personChannelModel.allArray.count ||
       indexPath.item >= self.personChannelModel.allArray[indexPath.section].count) {
        NSLog(@"invalid input");
        return;
    };
    
    // 点击其他section内的cell，则移动cell到第一个section，并且启动抖动动画和显示删除按钮
    NSInteger dstArraySize = self.personChannelModel.allArray[0].count;
    NSInteger insertItemIndex = dstArraySize == 0 ? 0 : dstArraySize - 1;
    
    // 1. 更新数据源
    ItemModel * item = self.personChannelModel.allArray[indexPath.section][indexPath.item];
    [self.personChannelModel.allArray[indexPath.section] removeObjectAtIndex:indexPath.item];
    [self.personChannelModel.allArray[0] insertObject:item atIndex:insertItemIndex];
    
    // 2. 通知UI更新
    NSIndexPath *dstIndexPath = [NSIndexPath indexPathForItem:insertItemIndex inSection:0];
    [self.personChannelView.collectionView moveItemAtIndexPath:indexPath toIndexPath:dstIndexPath];
    
    // 3. 启用抖动动画并显示删除按钮
    PersonCollectionViewCell *cell = (PersonCollectionViewCell *)[self.personChannelView.collectionView cellForItemAtIndexPath:dstIndexPath];
    [cell beginAnimation]; // 开启动画时顺便开启了按钮
    
    // 4. 添加点击按钮的事件
    [cell.cancelButton addTarget:self action:@selector(clickCellCancelButton:) forControlEvents:UIControlEventTouchUpInside];
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

@end
